package me.xlgp.xiquzimu.ui.changduan;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.google.android.material.snackbar.Snackbar;

import java.util.List;
import java.util.Objects;

import io.reactivex.rxjava3.disposables.CompositeDisposable;
import me.xlgp.xiquzimu.databinding.FragmentChangduanBinding;
import me.xlgp.xiquzimu.predicate.ChangDuanPredicate;
import me.xlgp.xiquzimu.ui.changci.ChangCiEditActivity;
import me.xlgp.xiquzimu.ui.changci.ChangCiViewActivity;
import me.xlgp.xiquzimu.view.ChangDuanSearchRecyclerviewLayout;

public class ChangDuanFragment extends Fragment {

    private final CompositeDisposable compositeDisposable = new CompositeDisposable();
    private FragmentChangduanBinding binding;
    private ChangDuanSearchRecyclerviewLayout searchRecyclerviewLayout;
    private ChangDuanViewModel viewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        binding = FragmentChangduanBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        searchRecyclerviewLayout = binding.zimuListSearchRecyclerviewLayout;

        viewModel = new ViewModelProvider(this).get(ChangDuanViewModel.class);
        viewModel.deleteState.observe(getViewLifecycleOwner(), s -> {
            Snackbar.make(requireView(), s, Snackbar.LENGTH_SHORT).show();
            cancel();
        });
        viewModel.loadState.observe(getViewLifecycleOwner(), s -> Snackbar.make(requireView(), s, Snackbar.LENGTH_SHORT).show());
        initSearchRecyclerviewLayout();

        ChangDuanListAdapter changDuanListAdapter = new ChangDuanListAdapter();
        changDuanListAdapter.setOnItemClickListener((itemView, view, data, position) -> toChangCiActivity(data.getId()));
        searchRecyclerviewLayout.setSearchListAdapter(changDuanListAdapter);
        searchRecyclerviewLayout.getRecyclerview().addItemDecoration(new ChangDuanListAdapter.GroupHeaderItemDecoration(changDuanListAdapter));
        viewModel.getChangduanList().observe(getViewLifecycleOwner(), list -> {
            searchRecyclerviewLayout.setRefreshing(false);
            if (list.size() == 0) {
                Toast.makeText(requireContext(), "没有唱词", Toast.LENGTH_SHORT).show();
            }
            setTotalCountTextView(list.size());
            changDuanListAdapter.updateData(list);
        });

        binding.edit.setOnClickListener(this::onEdit);
        binding.update.setOnClickListener(this::onFetch);
        binding.add.setOnClickListener(this::add);
        binding.selectAll.setOnClickListener(this::onSelectAll);
        binding.cancelButton.setOnClickListener(v -> cancel());
        binding.delete.setOnClickListener(this::onDelete);

        return root;
    }

    private void onDelete(View view) {
        ChangDuanListAdapter adapter = (ChangDuanListAdapter) searchRecyclerviewLayout.getRecyclerview().getAdapter();
        if (adapter != null) {
            List<Integer> idlist = adapter.getIdList();
            if (idlist.isEmpty()) {
                return;
            }
            createAlertDialog(adapter, idlist);
        }
    }

    private void createAlertDialog(ChangDuanListAdapter adapter, List<Integer> idlist) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("删除")
                .setMessage("所选项?")
                .setPositiveButton("确定", (dialog, which) -> viewModel.deleteChangDuanList(idlist))
                .setNegativeButton("取消", (dialog, which) -> {
                }).show();
    }

    private void onSelectAll(View view) {
        if (Objects.requireNonNull(viewModel.getChangduanList().getValue()).isEmpty()) {
            return;
        }
        ChangDuanListAdapter adapter = (ChangDuanListAdapter) searchRecyclerviewLayout.getRecyclerview().getAdapter();
        if (adapter != null) {
            adapter.selectAll();
            Button button = (Button) view;
            button.setText(adapter.getSelectAll() ? "反选" : "全选");
        }
    }

    //取消编辑状态
    private void cancel() {
        binding.editLayout.setVisibility(View.GONE);
        binding.linearLayout.setVisibility(View.VISIBLE);
        //取消所有的选择项
        ChangDuanListAdapter adapter = (ChangDuanListAdapter) searchRecyclerviewLayout.getRecyclerview().getAdapter();
        if (adapter != null) {
            adapter.setCheckEnable(false);
            adapter.setCancel();
        }
        initEditLayout();
    }

    private void initEditLayout() {
        binding.selectAll.setText("全选");
    }

    @Override
    public void onPause() {
        super.onPause();
        searchRecyclerviewLayout.clearFocus();
    }

    private void toChangCiActivity(Integer id) {
        Intent intent = new Intent(requireActivity(), ChangCiViewActivity.class);
        intent.putExtra("changduanID", id);
        startActivity(intent);
    }

    private void setTotalCountTextView(int count) {
        String text = "共有 " + count + " 项";
        binding.totalCountTextView.setText(text);
    }

    private void initSearchRecyclerviewLayout() {

        searchRecyclerviewLayout.build(this);
        searchRecyclerviewLayout.setRefreshing(true);
        searchRecyclerviewLayout.setPredicate(new ChangDuanPredicate(searchRecyclerviewLayout.getFilterCharSequenceLiveData()));
        searchRecyclerviewLayout.setOnRefreshListener(viewModel::loadChangDuanList);
    }

    public void add(View view) {
        Intent intent = new Intent(requireActivity(), ChangCiEditActivity.class);
        startActivity(intent);
    }

    public void onFetch(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("更新唱段")
                .setMessage("确认更新唱段?")
                .setPositiveButton("确定", (dialog, which) -> {
                    searchRecyclerviewLayout.setRefreshing(true);
                    compositeDisposable.add(viewModel.fetchChangDuanList().subscribe(id -> {
                    }, throwable -> Toast.makeText(requireContext(), throwable.getMessage(), Toast.LENGTH_SHORT).show()));
                })
                .setNegativeButton("取消", (dialog, which) -> {
                }).show();

    }

    public void onEdit(View view) {
        binding.linearLayout.setVisibility(View.GONE);
        binding.editLayout.setVisibility(View.VISIBLE);
        ChangDuanListAdapter adapter = (ChangDuanListAdapter) searchRecyclerviewLayout.getRecyclerview().getAdapter();
        if (adapter != null) {
            adapter.setCheckEnable(true);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}